<script setup>
import { ElButton, ElMessage } from 'element-plus'
import { SwitchButton } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { useStatusStore } from '../stores/status'
import { useConfigStore } from '../stores/config'
import { useDeviceStore } from '../stores/device'

const statusStore = useStatusStore()
const configStore = useConfigStore()
const devicesStore = useDeviceStore()

const btnLoading = ref(false)

const openSerial = async () => {
    btnLoading.value = true
    if (!configStore.initialized) {
        const success = await configStore.initConfig()
        if (!success) {
            ElMessage.error('配置加载失败，请检查服务器连接！')
        }
    } else {
        const res = await statusStore.openSerial()
        if (res) {
            ElMessage.success('串口打开成功')
            // 获取设备列表
            await devicesStore.initDevices(configStore.max_device_num)
        } else {
            ElMessage.error(
                '串口打开失败，请检查串口设置是否正确，上位机是否正确连接到电脑'
            )
        }
    }
    btnLoading.value = false
}

// onMounted(async () => {
//     const success = await openSerial()
//     if (success) {
//         ElMessage.success('串口打开成功')
//     } else {
//         ElMessage.error(
//             '串口打开失败，请检查串口设置是否正确，上位机是否正确连接到电脑'
//         )
//     }
// })
</script>

<template>
    <el-button
        type="success"
        @click="openSerial"
        :icon="SwitchButton"
        :loading="btnLoading"
        >打开串口</el-button
    >
</template>

<style scoped>
.mt20 {
    margin-top: 20px;
}

.controls {
    margin-top: 50px;
}

.sub-title {
    font-size: 24px;
    font-weight: bold;
    margin-top: 50px;
    margin-bottom: 20px;
    padding-left: 10px;
    border-left: 5px solid #409eff;
}
</style>
